$(function(){

    $( "#tb_sections tbody").sortable({
              revert: true,
              update: function( event, ui ) {
            	  var index = 1;
            	  var parentId = ui.item.data('parent');
            	  var id = ui.item.attr('id');
            	  var $tbody =  $(this);
            	  // Rebuilt the tree
            	  if(parentId != 'r0') {
            		  // Find new Top Parent
            		  var newIndex = $('#'+ui.item.attr('id')).index();
            		  if(newIndex == 0) {
            			  // You can't have a chidren without parent
            			  return false;
            		  } else {
            			  var $newParent = null;
            			  var parentIndex = 1;
            			  $tbody.find('tr[data-parent=r0]').each(function() {
            				  if(parentIndex > newIndex) {
            					  return;
            				  } else {
            					  $newParent = $(this);
            				  }
            				  parentIndex++;
            			  });
            			  // Reset New Node Parent
            			  var sectionid = $newParent.find('td.sectionid input').val();
            			  ui.item.find('td.sectionid input').val(sectionid);
            			  ui.item.find('td.changed input').val(true);
            			  ui.item.data('parent',$newParent.attr('id'));
            			  parentId = $newParent.attr('id');
            		  }
            	  } else {
            		  ui.item.find('td.changed input').val(true);
            		  var sectionid = ui.item.find('td.sectionid input').val();
            	  }
            	  
            	  function moveChildrens(id) {
            		  // Move All children to the new parent position
            		  $tbody.find('tr[data-parent='+id+']').each(function(){
                		  var $clonedRow = $(this).clone();
                		  ui.item.after($clonedRow);
                		  $(this).remove();
                		  $clonedRow.find('td.sectionid input').val(sectionid);
                		  moveChildrens($clonedRow.attr('id'));
                	  });
            	  }
            	  moveChildrens(id);
            	  
            	  if(parentId == 'r0') {
            		  $tbody.find('tr[data-parent=r0]').each(function() {
            			  $(this).find('td.position input').val(index);
                		  index++;
            		  });
            	  } else {
            		  $tbody.find('tr td.position input').each(function() {
            			  $(this).val(index);
                		  index++;
            		  });
            	  }
              }
        });
});